package com.example.springsecurity.exception;

import com.example.springsecurity.common.CommonResult;
import com.example.springsecurity.enums.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.nio.file.AccessDeniedException;

/**
 * @author wuancheng
 * @date 2024/6/12 17:59
 * @description 统一异常处理类
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 针对统一的业务异常类处理
     */
    @ExceptionHandler({Exception.class})
    public CommonResult exceptionHandler(Exception e){
        String errorCode = "";
        String errorDesc = "";
        if (e instanceof MySecurityException) {
            MySecurityException mySecurityException = (MySecurityException) e;
            errorCode = mySecurityException.getErrorCode();
            errorDesc = mySecurityException.getErrorDesc();
        } else if (e instanceof  AccessDeniedException) {

        } else {
            errorCode = ErrorCode.NO_PERMISSION.getErrorCode();
            errorDesc = ErrorCode.NO_PERMISSION.getErrorDesc();
        }
        logger.error(errorDesc, e);
        return CommonResult.failed(errorCode, errorDesc);
    }
}
